package com.wbao.dianniu.ui;


import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.powerfulrecyclerview.ptr.HistoryThemeHeaderView;
import com.powerfulrecyclerview.ptr.PowerfulRecyclerView;
import com.powerfulrecyclerview.ptr.SimDividerItemDecoration;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.timchat.utils.ChatActivity;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.ActivityInListAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.ActivityInListData;
import com.wbao.dianniu.expandtabview.FixedPopupWindow;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.listener.IActInConfirmListener;
import com.wbao.dianniu.listener.IActivityInListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.ActInConfirmManger;
import com.wbao.dianniu.manager.ActivityHelperManager;
import com.wbao.dianniu.manager.ActivityInListManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 报名管理
 *
 * @author yejianjun
 */
public class SignUpManagerActivity extends AppCompatActivity implements IActivityInListListener, OnClickListener,
        IActInConfirmListener, ActivityInListAdapter.OnItemClickListener {

    //    private PullToRefreshListView pullListView;
//    private ListView listView;
    private PowerfulRecyclerView recyclerView;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private TextView noDataTV;
    private ActivityInListManager manager;
    private ActInConfirmManger confirmManger;
    private ActivityInListAdapter adapter;
    //    private List<ActivityInListData> mList = new ArrayList<>();
    private int id;
    private TextView chooseTV;
    private ImageButton backBtn;
    private FixedPopupWindow popupwindow;
    private final Integer TYPE_ALL = null;
    private final Integer TYPE_PENDING = 1;
    private final Integer TYPE_AGREED = 2;
    private final Integer TYPE_REFUSED = 3;
    private Integer status = TYPE_ALL;

    private HistoryThemeHeaderView header;
    private int lastVisibleItem = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_signup_manager);
        initView();
        initData();
        initRecycler();
        initmPopupWindowView();
        initLoadMoreListener();
    }

    private void initView() {
        noDataTV = findViewById(R.id.no_find_data);
       /* pullListView = (PullToRefreshListView) findViewById(R.id.signup_manager_listview);
        pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        listView = pullListView.getRefreshableView();
        registerForContextMenu(listView);*/
        recyclerView = findViewById(R.id.signup_manager_listview);

        backBtn = findViewById(R.id.signup_back_button);
        chooseTV = findViewById(R.id.choose_status_tv);
        backBtn.setOnClickListener(this);
        chooseTV.setOnClickListener(this);
    }

    private void initData() {
        manager = new ActivityInListManager(this);
        manager.addActivityInListListener(this);
        confirmManger = new ActInConfirmManger(this);
        confirmManger.addActInConfirmListener(this);
        id = getIntent().getIntExtra(Const.BUNDLE_ID, 0);
        reqData(currentPage, status);
    }

    private void initRecycler() {
        adapter = new ActivityInListAdapter(this);
        adapter.setOnItemClickListener(this);
        adapter.changeMoreStatus(ActivityInListAdapter.PULLUP_LOAD_MORE);
        adapter.addData(new ArrayList<ActivityInListData>());
        recyclerView.setAdapter(adapter);
        // 设置布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        // 设置分割线
        recyclerView.addItemDecoration(new SimDividerItemDecoration(this));
        // 设置adapter
        header = (HistoryThemeHeaderView) LayoutInflater.from(this).inflate(R.layout.history_header_theme, recyclerView, false);
        recyclerView.setHeaderView(header);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshEnable(false);
    }

    /**
     * 上拉加载更多
     */
    private void initLoadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    //设置正在加载更多
                    adapter.changeMoreStatus(ActivityInListAdapter.LOADING_MORE);
                    // 上拉刷新 加载请求数据
                    pullUpRequest();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    /*OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            // 上拉刷新 加载请求数据
            pullUpRequest();
        }
    };*/

    // 上拉刷新数据请求
    private void pullUpRequest() {
        // 没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        reqData(currentPage, status);
    }

    private void reqData(int page, Integer type) {
        manager.activityInList(GlobalContext.getAccountId(), id, type, page * PAGE_COUNTS, PAGE_COUNTS);
    }

    @Override
    public void onActivityInListFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
//        pullListView.onRefreshComplete(false, false);
        adapter.changeMoreStatus(ActivityInListAdapter.NO_LOAD_MORE);
    }

    @Override
    public void onActivityInListSuccess(List<ActivityInListData> list) {
//        pullListView.onRefreshComplete(false, false);
        if (null != list) {
            adapter.addData(list);
            if (adapter.getList().size() == 0) {
                noDataTV.setVisibility(View.VISIBLE);
            } else {
                noDataTV.setVisibility(View.GONE);
            }
        }
        adapter.changeMoreStatus(ActivityInListAdapter.NO_LOAD_MORE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_status_tv:
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                    return;
                } else {
                    popupwindow.showAsDropDown(v, 0, 0);
                }
                break;
            case R.id.signup_back_button:
                finish();
                break;
            case R.id.signup_pop_all:
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                }
                chooseTV.setText("全部");
                adapter.clear();
                currentPage = 0;
                status = TYPE_ALL;
                reqData(currentPage, status);
                break;
            case R.id.signup_pop_pending:
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                }
                chooseTV.setText("待处理");
                adapter.clear();
                currentPage = 0;
                status = TYPE_PENDING;
                reqData(currentPage, status);
                break;
            case R.id.signup_pop_agreed:
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                }
                chooseTV.setText("已同意");
                adapter.clear();
                currentPage = 0;
                status = TYPE_AGREED;
                reqData(currentPage, status);
                break;
            case R.id.signup_pop_refused:
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                }
                chooseTV.setText("已拒绝");
                adapter.clear();
                currentPage = 0;
                status = TYPE_REFUSED;
                reqData(currentPage, status);
                break;
            default:
                break;
        }
    }

    public void initmPopupWindowView() {
        // // 获取自定义布局文件pop.xml的视图  
        View customView = getLayoutInflater().inflate(R.layout.signup_popview, null, false);
        // 创建PopupWindow实例,200,150分别是宽度和高度  
        popupwindow = new FixedPopupWindow(customView, Utils.dip2px(this, 120), LinearLayout.LayoutParams.WRAP_CONTENT);
        popupwindow.setOutsideTouchable(true);
        customView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                }
                return false;
            }
        });
        /** 在这里可以实现自定义视图的功能 */
        Button btton1 = customView.findViewById(R.id.signup_pop_all);
        Button btton2 = customView.findViewById(R.id.signup_pop_pending);
        Button btton3 = customView.findViewById(R.id.signup_pop_agreed);
        Button btton4 = customView.findViewById(R.id.signup_pop_refused);
        btton1.setOnClickListener(this);
        btton2.setOnClickListener(this);
        btton3.setOnClickListener(this);
        btton4.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        if (popupwindow != null && popupwindow.isShowing()) {
            popupwindow.dismiss();
            popupwindow = null;
        }
        if (null != manager) {
            manager.removeActivityInListListener(this);
        }
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void onActInConfirmFailure(int errorCode, String errorMsg) {
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onActInConfirmSuccess(int accountId, int activityId, int status) {
        if (status == 2) {
            ActivityHelperManager.getInstance().IsChanged(activityId, accountId, 4);
            adapter.statusChange(activityId, accountId, 2);
        } else if (status == 3) {
            ActivityHelperManager.getInstance().IsChanged(activityId, accountId, 4);
            adapter.statusChange(activityId, accountId, 3);
        }
    }

    @Override
    public void itemClick(View v) {
        int position;
        final ActivityInListData data;
        switch (v.getId()) {
            case R.id.already_agreed:
                position = (Integer) v.getTag(R.id.already_agreed);
                data = adapter.getList().get(position);
                confirmManger.inconfirm(data.getAccountId(), data.getActivityId(), 2);
                break;
            case R.id.already_refuse:
                position = (Integer) v.getTag(R.id.already_refuse);
                data = adapter.getList().get(position);
                confirmManger.inconfirm(data.getAccountId(), data.getActivityId(), 3);
                break;
            case R.id.already_call:
                position = (Integer) v.getTag(R.id.already_call);
                data = adapter.getList().get(position);
                CustomDialog.Builder builder = new CustomDialog.Builder(this);
                builder.setTitle("确认拨打电话：" + data.getMobile());
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //调用拨打电话
                                PermissionUtils.getInstance().intentToCall(SignUpManagerActivity.this, data.getMobile());
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.already_send_msn:
                position = (Integer) v.getTag(R.id.already_send_msn);
                data = adapter.getList().get(position);
                // 发短信
                PermissionUtils.getInstance().intentToSendSMS(this, data.getMobile(), "");
                break;
            case R.id.already_send_msg:
                position = (Integer) v.getTag(R.id.already_send_msg);
                data = adapter.getList().get(position);
                //跳转到聊天界面
                /*String appkey = getResources().getString(R.string.app_key);
                GlobalUserData userData = new GlobalUserData();
                LoginSampleHelper.getInstance().openChat(this, userData.getEnvironemt() + data.getAccountId() + "", appkey);*/
                GlobalUserData userData = new GlobalUserData();
                ChatActivity.navToChat(this, userData.getEnvironemt() + String.valueOf(data.getAccountId()), TIMConversationType.C2C,GlobalContext.cdndownUrl + data.getHeadPic(),data.getRealName(),GlobalContext.cdndownUrl + GlobalContext.getHeadPic());
                break;
            default:
                break;
        }
    }
}
